package fr.obsmip.sedoo.server.service;

import java.util.ArrayList;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.obsmip.sedoo.client.service.DirectoryService;
import fr.obsmip.sedoo.core.RBVApplication;
import fr.obsmip.sedoo.core.dao.GeonetworkObservatoryDAO;
import fr.obsmip.sedoo.core.dao.ObservatoryPersonDAO;
import fr.obsmip.sedoo.core.domain.GeonetworkObservatory;
import fr.obsmip.sedoo.core.domain.ObservatoryPerson;
import fr.obsmip.sedoo.server.service.dtotool.ObservatoryPersonDTOTools;
import fr.obsmip.sedoo.shared.domain.ObservatoryPersonDTO;
import fr.sedoo.commons.client.util.ServiceException;
import fr.sedoo.metadata.shared.domain.dto.PersonDTO;

public class DirectoryServiceImpl extends RemoteServiceServlet implements
DirectoryService {

	ObservatoryPersonDAO dao = null;
	GeonetworkObservatoryDAO observatoryDAO = null;

	public DirectoryServiceImpl() 
	{
	}

	@Override
	public Boolean deletePerson(String id) throws ServiceException {
		try
		{
			initDao();
			dao.delete(new Long(id));
			return true;
		}
		catch (Exception e)
		{
			throw new ServiceException(e.getMessage());
		}
	}

	@Override
	public ArrayList<PersonDTO> loadPersons(String observatoryId) throws ServiceException {
		initDao();
		ArrayList<ObservatoryPerson> aux = dao.findByObservatoryId(observatoryId);
		ArrayList<PersonDTO> result = new ArrayList<PersonDTO>();
		for (ObservatoryPerson observatoryPerson : aux) {
			result.add(ObservatoryPersonDTOTools.toDTO(observatoryPerson));
		}
		return result;
	}

	@Override
	public void savePerson(ObservatoryPersonDTO person) throws ServiceException {
		try
		{
			initDao();
			Long observatoryId = person.getObservatoryId();
			GeonetworkObservatory observatory = observatoryDAO.findObservatoryById(observatoryId);
			ObservatoryPerson dto = ObservatoryPersonDTOTools.fromDTO(person);
			dto.setObservatory(observatory);
			dao.save(dto);
		}
		catch (Exception e)
		{
			throw new ServiceException(e.getMessage());
		}
	}

	private void initDao()
	{
		if (dao == null)
		{
			dao = RBVApplication.getInstance().getObservatoryPersonDAO();
		}
		
		if (observatoryDAO == null)
		{
			observatoryDAO = RBVApplication.getInstance().getGeonetworkObservatoryDAO();
		}
	}


}

